$(function (){
    var key = getcookie('key');
    if(key==''){
        window.location.href = WapSiteUrl+'/tmpl/member/login.php';
    }else{
        //初始化页面数据
        function initCartList(){
             $.ajax({
                url:ApiUrl+"/index.php?act=member_cart&op=cart_list",
                type:"post",
                dataType:"json",
                data:{key:key},
                success:function (result){
                    console.log(result)
                    if(checklogin(result.login)){
                        if(!result.datas.error){
                            var rData = result.datas;
                            rData.WapSiteUrl = WapSiteUrl;
                            var html = template.render('cart-list', rData);
                            $("#cart-list-wp").html(html);
                            //删除购物车
                            $(".cart-list-del").click(delCartList);
                             //购买数量，减
                            $(".minus-wp").click(minusBuyNum);
                            //购买数量加
                            $(".add-wp").click(addBuyNum);
                            //去结算
                            $(".goto-settlement").click(goSettlement);
                            $(".buynum").blur(buyNumer);


                            $('.cart-litem-wp').each(function(){
                                var h = $(this).height();
                                $(this).find('.cart-litemw-imgwp').css({
                                    marginTop : (h - 100)/2
                                })
                            })
                        }else{
                           alert(result.datas.error);
                        }
                    }
                }
            });
        }
        initCartList();
        //删除购物车
        function delCartList(){
            var  cart_id = $(this).attr("cart_id");
            $.ajax({
                url:ApiUrl+"/index.php?act=member_cart&op=cart_del",
                type:"post",
                data:{key:key,cart_id:cart_id},
                dataType:"json",
                success:function (res){
                    if(checklogin(res.login)){
                        if(!res.datas.error && res.datas == "1"){
                            initCartList();
                        }else{
                            alert(res.datas.error);
                        }
                    }
                }
            });
        }
        //购买数量减
        function minusBuyNum(){
            var self = this;
            editQuantity(self,"minus");
        }
        //购买数量加
        function addBuyNum(){
            var self = this;
            editQuantity(self,"add");
        }
        //购买数量增或减，请求获取新的价格
        function editQuantity(self,type){
            var sPrents = $(self).parents(".cart-litemw-cnt")
            var cart_id = sPrents.attr("cart_id");
            var numInput = sPrents.find(".buy-num");
            var buynum = parseInt(numInput.val());
            var quantity = 1;
            if(type == "add"){
                quantity = parseInt(buynum+1);
                // 
            }else {
                if(buynum >1){
                    quantity = parseInt(buynum-1);
                }else {
                    $.sDialog({
                        skin:"red",
                        content:'购买数目必须大于1',
                        okBtn:false,
                        cancelBtn:false
                    });
                    return;
                }
            }
            $.ajax({
                url:ApiUrl+"/index.php?act=member_cart&op=cart_edit_quantity",
                type:"post",
                data:{key:key,cart_id:cart_id,quantity:quantity},
                dataType:"json",
                success:function (res){
                    if(checklogin(res.login)){
                        if(!res.datas.error){
                            numInput.val(quantity);
                            sPrents.find(".goods-total-price").html(res.datas.total_price);
                            var goodsTotal = $(".goods-total-price");
                            var totalPrice = parseFloat("0.00");
                            for(var i = 0;i<goodsTotal.length;i++){
                                totalPrice += parseFloat($(goodsTotal[i]).html());
                            }
                            $(".total_price").html("￥"+totalPrice.toFixed(2));
                        }else{
                            $.sDialog({
                                skin:"red",
                                content:res.datas.error,
                                okBtn:false,
                                cancelBtn:false
                            });
                        }
                    }
                }
            });
        }

        var show_license = false;
        //去结算
        function goSettlement(){
            if($(".cart-checked-id:checked").length<1){
                $.sDialog({
                    skin:"red",
                    content:'请选择结算商品！',
                    okBtn:false,
                    cancelBtn:false
                });
                return false;
            }
            if($('.tax').length && !show_license){
                $.get("/gaozhishu.txt",function (txt) {
                    layer.open({
                        content: txt,
                        btn: '我清楚',
                        shadeClose: false,
                        style : "max-height:300px;overflow:auto",
                        yes: function(){
                            show_license = true;
                            goSettlement();
                        }
                    });
                });
                return;
            }
            //购物车ID
            var cartIdArr = [];
            $(".cart-checked-id:checked").each(function(){
                var cartId = $(this).attr("cart_id");
                var cartNum = $(this).siblings(".cart-litemw-cnt").find(".buynum").val();
                var cartIdNum = cartId+"|"+cartNum;
                cartIdArr.push(cartIdNum);
            });
            var cart_id = cartIdArr.toString();

            //判断是否要拆单
            //杭州海关不拆分订单
            if(custom_name != 'hangzhou' && order_split){
                var flag = false;
                $('.cart-list-item').each(function(){
                    var tax = 0;
                    $(this).find('.cart-litem-wp').each(function(){
                        var single_tax = $(this).find('.tax em').text();
                        var num = $(this).find('.buynum').val();
                        var result = single_tax * num;
                        if(result === result){
                            tax += result;
                        }
                    });

                    if(tax > split_limit){
                        flag = true;
                    }

                });

                //如果满足拆分条件
                if(flag){
                    //如果开启了提示
                    if(manual_split){
                        layer.open({
                            title: '温馨提示',
                            content: '您的订单已产生行邮税，系统可能会将订单拆分，确认拆分吗？',
                            btn: ['嗯', '不要'],
                            yes: function(index){
                                // location.reload();
                                layer.close(index);
                                var index = layer.open({
                                    type : 2
                                });
                                $.get('/shop/index.php?act=seccode&op=want_split',function(){
                                    window.location.href = WapSiteUrl + "/tmpl/order/buy_step1.html?ifcart=1&cart_id="+cart_id + '&version=' + Math.random();
                                });
                            },
                            no : function(index){
                                var index = layer.open({
                                    type : 2
                                });
                                $.get('/shop/index.php?act=seccode&op=dont_split',function(){
                                    window.location.href = WapSiteUrl + "/tmpl/order/buy_step1.html?ifcart=1&cart_id="+cart_id + '&version=' + Math.random();
                                })
                            }
                        }); 
                        return;

                    }
                    else{
                        var index = layer.open({
                            type : 2
                        });
                        $.get('/shop/index.php?act=seccode&op=want_split',function(){
                            window.location.href = WapSiteUrl + "/tmpl/order/buy_step1.html?ifcart=1&cart_id="+cart_id + '&version=' + Math.random();
                        });
                        return;
                    }
                }

            }
            window.location.href = WapSiteUrl + "/tmpl/order/buy_step1.html?ifcart=1&cart_id="+cart_id + '&version=' + Math.random();

        }
        //验证
        $.sValid.init({
            rules:{
                buynum:"digits"
            },
            messages:{
                buynum:"请输入正确的数字"
            },
            callback:function (eId,eMsg,eRules){
                if(eId.length >0){
                    var errorHtml = "";
                    $.map(eMsg,function (idx,item){
                        errorHtml += "<p>"+idx+"</p>";
                    });
                    $.sDialog({
                        skin:"red",
                        content:errorHtml,
                        okBtn:false,
                        cancelBtn:false
                    });
                }
            }  
        });
        function buyNumer(){
            $.sValid();
        }

        $(document).on("click", "#checkall", function(){
            $('.cart-checked-id').prop('checked',this.checked);
            $('.checked-store').prop('checked',this.checked)
        })
        $(document).on("click", ".checked-store", function(){
            $(this).parents(".cart-list-item").find(".cart-checked-id").prop('checked',this.checked);
            setCheckAllStatus();
        });
        $(document).on("click", ".cart-checked-id", function(){
            var _parent = $(this).parents(".cart-list-item");
            console.log(_parent.find(".cart-checked-id").length, _parent.find(".cart-checked-id:checked").length);
            if(_parent.find(".cart-checked-id").length == _parent.find(".cart-checked-id:checked").length){
                _parent.find(".checked-store").prop('checked', true);
            }else{
                _parent.find(".checked-store").prop('checked', false);
            }
            setCheckAllStatus();
        });

        function setCheckAllStatus(){
            if($(".cart-checked-id:checked").length == $(".cart-checked-id").length){
                $("#checkall").prop('checked', true);
            }else{
                $("#checkall").prop('checked', false);
            }
        }


    }
});